import os

from dotenv import load_dotenv
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging

load_dotenv()

secret_id = os.getenv("COS_SECRET_ID")
secret_key = os.getenv("COS_SECRET_KEY")

# 设置日志级别，DEBUG|INFO|WARNING|ERROR|CRITICAL
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 替换成你的存储桶所在区域
region = 'ap-shanghai'

# 替换成你的存储桶名称
bucket_name = 'ai-1253740002'

print(secret_id)
print(secret_key)

# 初始化客户端配置
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
client = CosS3Client(config)


def upload_file_to_cos(file_path, key):
    """
    上传文件到 COS
    :param file_path: 本地文件路径
    :param key: COS 中的文件名
    :return: 下载链接
    """
    try:
        response = client.upload_file(
            Bucket=bucket_name,
            LocalFilePath=file_path,
            Key=key,
            PartSize=10,
            MAXThread=10,
            EnableMD5=False
        )
        print("Upload Success.")

        # 如果你的存储桶是公共读，可以直接通过这个URL访问
        public_url = f"https://{bucket_name}.cos.{region}.myqcloud.com/{key}"

        # 获取带签名的临时下载链接
        signed_url = client.get_presigned_download_url(Bucket=bucket_name, Key=key, Expired=3600)  # 有效期为1小时

        return public_url, signed_url
    except Exception as e:
        print(f"Upload failed. {e}")
        return None, None



